﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Consul;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.Gateway;
using Wicture.Microservice.DbProviders;

namespace Wicture.QPZS.EPC.API.DockerDbGatewayTest
{
    public class EpcApiDbGateway : IEpcApiDbGateway
    {
        private readonly IMicroserviceDbGateway _dockerDbGateway;

        private static Lazy<List<DbRouteDatabase>> DbRoutes = new Lazy<List<DbRouteDatabase>>(Load);

        private static IConfiguration frameworkConfiguration;

        public EpcApiDbGateway(IConfiguration configuration, IMicroserviceDbGateway dockerDbGateway)
        {
            frameworkConfiguration = configuration;
            _dockerDbGateway = dockerDbGateway;
        }

        private static List<DbRouteDatabase> Load()
        {
            return frameworkConfiguration?.GetSection("Databases").Get<List<DbRouteDatabase>>()
                ?? ConfigurationManager.Settings.GetConfig<List<DbRouteDatabase>>("Databases");
        }

        public DatabaseConnection Process(HttpContext context, JToken param, IdentityInfo userInfo)
        {
            var module = context.Request.Headers.FirstOrDefault(s => s.Key.Equals("module", StringComparison.CurrentCultureIgnoreCase)).Value.ToString();

            var database = DbRoutes.Value.FirstOrDefault(r => r.Modules.Contains(module));
            if (database == null)
            {
                throw new Exception($"No DbRoute configured for brand: {module}.");
            }

            var connectionString = _dockerDbGateway.Process(database.Name);

            return new DatabaseConnection
            {
                ReadConnectionString = connectionString,
                WriteConnectionString = connectionString
            };
        }
    }
}
